package cn.com.acca.ma.jpa.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * jpa工具类
 * @author lishen
 *
 */
public class JpaUtil {
	private static EntityManagerFactory entityManagerFactory;
	static {
		try {
			entityManagerFactory = Persistence.createEntityManagerFactory("movingAverage");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 返回同一个entityManagerFactory的entityManager
	 * @return
	 */
	public static EntityManager currentEntityManager() {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		return entityManager;
	}

	/**
	 * 关闭同一个entityManagerFactory的entityManager
	 * @param entityManager
	 */
	public static void closeEntityManager(EntityManager entityManager) {
		if (null != entityManager) {
			entityManager.close();
		}
	}

	/**
	 * 创建一个新的EntityManagerFactory，并返回新的EntityManager
	 * @return
	 */
	public static EntityManager newEntityManager(){
		EntityManagerFactory newEntityManagerFactory = Persistence.createEntityManagerFactory("movingAverage");
		return newEntityManagerFactory.createEntityManager();
	}
}
